﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Security.Cryptography;
using System.Text;
using System.Windows.Forms;
using System.IO;
using System.Xml;


namespace RsaRegister
{
    public partial class FrmLicfileGenerator : Form
    {
        
        string pubKey;
        string priKey;
        string targPath = Environment.SpecialFolder.Personal.ToString();// Default to the My Documents folder.
        public FrmLicfileGenerator()
        {
            InitializeComponent();
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            string fname = Application.StartupPath + "\\APPs.txt";
            if(File.Exists(fname))
            {
                string[] lines = File.ReadAllLines(fname);
                cbSoftware.Items.Clear();
                foreach (string line in lines)
                {
                    cbSoftware.Items.Add(line);
                }
            }
            dtpExpDate.Value = DateTime.Now.AddYears(1);
            
        }

        private void btnGenKeys_Click(object sender, EventArgs e)
        {
            try
            {
                RsaServer rsaServer = new RsaServer();
                rsaServer.GenerateKeys();
                pubKey = rsaServer.pubKey;
                priKey = rsaServer.priKey;
                FolderBrowserDialog fb = new FolderBrowserDialog
                {
                    Description = "选择输出文件目录",
                    SelectedPath = Application.StartupPath,
                  
                };
                if (fb.ShowDialog() == DialogResult.OK)
                {
                    targPath = fb.SelectedPath + "\\" + cbSoftware.Text;
                    if (!Directory.Exists(targPath))
                        Directory.CreateDirectory(targPath);
                    string pubFile = targPath + "\\PubKey.key";
                    File.WriteAllText(pubFile, pubKey);
                    string priFile = targPath + "\\PriKey.key";
                    File.WriteAllText(priFile, priKey);
                    System.Diagnostics.Process.Start(targPath);
                }
                
            }
            catch(Exception ex)
            {
                MessageBox.Show(ex.Message,"Error",MessageBoxButtons.OK,MessageBoxIcon.Error);
            }
            
        }

        private void cbSoftware_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (!string.IsNullOrEmpty(cbSoftware.Text))
            {
                btnGenKeys.Enabled = true;
                btnLoadPrikey.Enabled = true;
                btnLoadPubkey.Enabled = true;
            }
           
        }

        private void txtUser_TextChanged(object sender, EventArgs e)
        {
            if(!string.IsNullOrEmpty(priKey))
            {
                btnGenRegCode.Enabled = true;
                
            }
        }

        private void chkCpu_CheckedChanged(object sender, EventArgs e)
        {
            HardwareInfo hw=new HardwareInfo();
            if(chkCpu.Checked)
            {
                try
                {
                    txtCpuid.Text = hw.GetCpuID();
                }
                catch(Exception ex)
                {
                    MessageBox.Show(ex.Message,"Error while Geting CPU ID",MessageBoxButtons.OK,MessageBoxIcon.Error);
                }
            }
            else
            { txtCpuid.Text = ""; }
        }
        private RegInfo BuildRegInfo()
        {
            RegInfo regInfo = new RegInfo
            {
                SoftName = cbSoftware.Items[cbSoftware.SelectedIndex].ToString().Trim(),
                User = txtUser.Text,
                Cpuid = txtCpuid.Text,
                Guid = new Guid( txtGuid.Text),
                ExpireDate = dtpExpDate.Value,
                TotalUsers = Convert.ToInt32(txtTotalUsers.Text)
            };

            return regInfo;
        }

        private void txtUserstring_TextChanged(object sender, EventArgs e)
        {
            if(string.IsNullOrEmpty(txtUserstring.Text)||string.IsNullOrEmpty(pubKey))
            {
                btnEncrypt.Enabled = false;
            }
            else
            {
                btnEncrypt.Enabled = true;
            }
        }

        private void txtEncryptString_TextChanged(object sender, EventArgs e)
        {
            if(string.IsNullOrEmpty(txtEncryptString.Text)||(string.IsNullOrEmpty(priKey)))
            {
               
                btnDecryString.Enabled = false;
            }
            else
            {
                
                btnDecryString.Enabled = true;
            }
        }

        private void btnEncrypt_Click(object sender, EventArgs e)
        {
            RsaClient rclient = new RsaClient(pubKey);
            txtEncryptString.Text = rclient.RSAEncrypt(txtUserstring.Text);
        }

        private void btnDecryString_Click(object sender, EventArgs e)
        {
            RsaServer rcode = new RsaServer(priKey);
            txtDecryptedString.Text = rcode.RSADecrypt(txtEncryptString.Text);
        }

        private void chkGuid_CheckedChanged(object sender, EventArgs e)
        {
            if(chkGuid.Checked)
            {
                
                txtGuid.Text = Guid.NewGuid().ToString("D");
            }
            else
            { txtGuid.Text = ""; }
        }

        private void btnUserstring_Click(object sender, EventArgs e)
        {
            txtUserstring.Text = BuildRegInfo().GenerateRegString();
        }

        private void btnLoadPrikey_Click(object sender, EventArgs e)
        {
            string keyFile = "";
            OpenFileDialog fd = new OpenFileDialog();

            fd.InitialDirectory = targPath;
            fd.Filter = "key files (*.key)|*.key|All files (*.*)|*.*";
            fd.FilterIndex = 1;
            fd.Title = "Specify Private Key File";
            if (fd.ShowDialog() == DialogResult.OK)
            {
                targPath = Path.GetDirectoryName(fd.FileName);
                keyFile = fd.FileName;
                priKey = File.ReadAllText(keyFile);
                pubKey= priKey.Substring(0, priKey.IndexOf("<P>")) + "</RSAKeyValue>";
                txtUser.Enabled = true;
                txtEncryptString.Enabled = true;
                btnLoadLicfile.Enabled = true;
                txtUserstring.Enabled = true;
                txtEncryptString.Enabled = true;

            }
        }

        private void btnLoadPubkey_Click(object sender, EventArgs e)
        {
            string keyFile = "";
            OpenFileDialog fd = new OpenFileDialog
            {
                InitialDirectory = targPath,
                Filter = "key files (*.key)|*.key|All files (*.*)|*.*",
                FilterIndex = 1,
                Title = "Specify Public Key File"
            };
            if (fd.ShowDialog() == DialogResult.OK)
            {
                targPath = Path.GetDirectoryName(fd.FileName);
                keyFile = fd.FileName;
                pubKey = File.ReadAllText(keyFile);
                btnLoadLicfile.Enabled = true;
                txtUserstring.Enabled = true;
                if (txtRegCode.Text != "")    btnVerify.Enabled = true;
            }
        }

        private void btnGenRegfile_Click(object sender, EventArgs e)
        {
            
            RsaServer rsaServer = new RsaServer( priKey);
            RegInfo regInfo = BuildRegInfo();
            FolderBrowserDialog fb = new FolderBrowserDialog
            {
                Description = "选择输出文件目录",
                SelectedPath = targPath
            };
            if (fb.ShowDialog() == DialogResult.OK)
            {
                targPath = fb.SelectedPath;
                string licfile = targPath + "\\" + txtUser.Text + ".lic";
                if (File.Exists(licfile)) File.Delete(licfile);
                rsaServer.GenerateLicFile(licfile, regInfo);
                System.Diagnostics.Process.Start(targPath);
            }
                
        }
       
        private void btnVerify_Click(object sender, EventArgs e)
        {
            RsaClient rclient = new RsaClient(pubKey);
            string ustring = BuildRegInfo().GenerateRegString();
            bool res = rclient.VerifyRegisterCode(txtRegCode.Text, ustring);
            if (res)
            {
                lbMatch.ForeColor = Color.Green;
                lbMatch.Text = "Match";
            }
            else
            {
                lbMatch.ForeColor = Color.Red;
                lbMatch.Text = "Mismatch!";
            }
        }

        private void btnLoadLicfile_Click(object sender, EventArgs e)
        {
            string keyFile = "";
            OpenFileDialog fd = new OpenFileDialog
            {
                InitialDirectory = targPath,
                Filter = "lic files (*.dat,*.lic)|*.dat;*.lic|lic files (*.lic)|*.lic|All files (*.*)|*.*",
                FilterIndex = 1,
                Title = "Registration File"
            };
            if (fd.ShowDialog() == DialogResult.OK)
            {
                targPath = Path.GetDirectoryName(fd.FileName);
                keyFile = fd.FileName;
                RsaClient rclient = new RsaClient(pubKey);
                RegInfo regInfo = rclient.GetRegInfoFromLicFile(keyFile, out string rcode);
                txtRegCode.Text = rcode;
                txtUser.Text = regInfo.User;
                if (!string.IsNullOrEmpty(rcode))  btnVerify.Enabled = true;
                if(!string.IsNullOrEmpty(pubKey))
                {
                    RsaClient rsaclient = new RsaClient(pubKey);
                    eAuthStatus res = rsaclient.AuthorizeCheck(keyFile);
                    MessageBox.Show(res.ToString());
                }
                
            }
        }

        private void btnGenRegCode_Click(object sender, EventArgs e)
        {
            btnGenRegfile.Enabled = true;
            RsaServer rsaServer = new RsaServer(priKey);
            RegInfo regInfo = BuildRegInfo();
            txtRegCode.Text = rsaServer.GenerateRegisterCode(regInfo);

        }

        private void label4_Click(object sender, EventArgs e)
        {

        }
    }
    

}
